"""
/***************************************************************************
BioidxDialog
A QGIS plugin
Calculate the biodiversity index
                             -------------------
begin                : 2009-08-03 
copyright            : (C) 2009 by Mark Baas
email                : mark.baas123@gmail.com 
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

from Ui_Bioidx import Ui_Bioidx
from qgis.core import *
from qgis.gui import *

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import os



# create the dialog for zoom to point
class BioidxDialog(QDialog):
    def __init__(self, cb_ok): 
        QDialog.__init__(self) 
        
        self.cb_ok = cb_ok
        
        # Set up the user interface from Designer. 
        self.ui = Ui_Bioidx()
        self.ui.setupUi(self) 

        # Load layer in to combox
        layermap = QgsMapLayerRegistry.instance().mapLayers()
        layerlist = []
        for name, layer in layermap.iteritems():
            layerlist.append(unicode(layer.name()))  

        if len(layerlist) < 2: 
            msgBox = QMessageBox()
            msgBox.setText(QCoreApplication.translate("EcoGis", "You have to add at least two layers, one target layer, one layer representing species observations"))
            msgBox.exec_()
            self.exec_ = self.show = self._close
            return 
            
        self.ui.layerPlaces.addItems(layerlist)
        self.ui.layerHabitats.addItems(layerlist)
        
        self.getSourceFields()

        # connect file dialog
        #QObject.connect( self.ui.btnBrowse, SIGNAL( "clicked()" ), self.outFile )
        
        QObject.connect(self.ui.buttonBox, SIGNAL("accepted()"), self._accept)
        QObject.connect(self.ui.layerHabitats, SIGNAL("currentIndexChanged(QString)"), self.getSourceFields)
        QObject.connect(self.ui.btnBrowse, SIGNAL("clicked()"), self.browseFile)
        

        
    def _accept(self):
        self.setResult(1)
        self.cb_ok(self)

        self.hide()
        
    def _close(self):
        self.setResult(0)
        if self.cb_ok(None):
            self.hide()
        
    def getSourceFields(self, *args):
        self.ui.sourceField.clear()
        layer = self.getLayer("habitats")
        fields = layer.dataProvider().fields()
        for i in fields:
            name = fields[i].name()
            self.ui.sourceField.addItem(name)
            

    def outFile(self):
        settings = QSettings()
        dirName = settings.value( "/UI/lastShapefileDir" ).toString()
        filtering = QString( "Shapefiles (*.shp)" )
        encode = settings.value( "/UI/encoding" ).toString()
        fileDialog = QgsEncodingFileDialog( self, "Save output shapefile", dirName, filtering, encode )
        fileDialog.setDefaultSuffix( QString( "shp" ) )
        fileDialog.setFileMode( QFileDialog.AnyFile )
        fileDialog.setAcceptMode( QFileDialog.AcceptSave )
        fileDialog.setConfirmOverwrite( True )
        if not fileDialog.exec_() == QDialog.Accepted:
		    return None, None
        files = fileDialog.selectedFiles()
        settings.setValue("/UI/lastShapefileDir", QVariant( QFileInfo( unicode( files.first() ) ).absolutePath() ) )
        self.shapefileName, self.encoding = ( unicode( files.first() ), unicode( fileDialog.encoding() ) )
        self.ui.outputFilename.setText(self.shapefileName)

    def getLayer(self, layerName):
        if layerName == "places":
            myName = self.ui.layerPlaces.currentText()
            
        elif layerName == "habitats":
            myName = self.ui.layerHabitats.currentText()
        
        layermap = QgsMapLayerRegistry.instance().mapLayers()
        for name, layer in layermap.iteritems():
            if layer.type() == QgsMapLayer.VectorLayer and layer.name() == myName:
                if layer.isValid():
                    return layer
                else:
                    return None
                    
    def getSourceField(self):
        return str(self.ui.sourceField.currentText())

    def getDistance(self):
        return 0#int(self.ui.bufferDistance.value())

    def getHField(self):
        return str(self.ui.fieldName.text())
       
    def getEField(self):
        return str(self.ui.fieldName2.text())

    def getOutputFilename(self):
        return str(self.ui.outputFilename.text())
        
    def getHabitatDefinitions(self):
        return str(self.ui.definitionsFile.text())

    def browseFile(self):
        filename = str(QFileDialog().getOpenFileName(self, 'Open definitions file', os.getcwd()))
        self.ui.definitionsFile.setText(filename)
